package com.horizon.im.imServer.serverProcessor;

import com.horizon.im.common.ProtocolInstant;
import com.horizon.im.common.bean.UserDTO;
import com.horizon.im.common.bean.msg.ProtoMsg;
import com.horizon.im.imServer.protoBuilder.LoginResponseBuilder;
import com.horizon.im.imServer.server.session.LocalSession;
import com.horizon.im.imServer.server.session.service.SessionManager;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 服务器端登录专门有个处理类，当requestHandler收到pipeline的信息后
 * 就异步调用这个处理类，因为涉及到校验，比较耗时需要专门异步处理
 */
@Data
@Slf4j
@Service("LoginProcessor")
public class LoginProcessor extends AbstractServerProcessor {
    @Autowired
    LoginResponseBuilder loginResponseBuilder;
    @Autowired
    SessionManager sessionManager;

    @Override
    public ProtoMsg.HeadType op() {
        return ProtoMsg.HeadType.LOGIN_RESPONSE;
    }

    @Override
    public Boolean action(LocalSession localSession, ProtoMsg.Message msg) {
        //取出token进行验证
        ProtoMsg.LoginRequest info = msg.getLoginRequest();

        long seqNo = msg.getSequence();
        UserDTO user = UserDTO.fromMsg(info);
        //检查用户
        boolean isValidUser = checkUser(user);

        if (!isValidUser) {
            ProtocolInstant.ResultCodeEnum resultCode = ProtocolInstant.ResultCodeEnum.NO_TOKEN;
            ProtoMsg.Message response =
                    loginResponseBuilder.loginResponse(resultCode, seqNo, localSession.getSessionId());
            //发送之后，断开链接
            localSession.writeAndClose(response);
            return false;
        }

        localSession.setUserDTO(user);
        //绑定session和channel之间的正向导航和反向导航
        localSession.bind();
        //记录进程级缓存和redis缓存
        sessionManager.addLocalSession(localSession);

        //通知客户端，登录成功
        ProtocolInstant.ResultCodeEnum resultCode = ProtocolInstant.ResultCodeEnum
                .SUCCESS;
        ProtoMsg.Message response = loginResponseBuilder.loginResponse(resultCode,
                seqNo, localSession.getSessionId());

        localSession.writeAndFlush(response);
        return true;
    }

    private boolean checkUser(UserDTO user)
    {

        //校验用户,比较耗时的操作,需要100 ms以上的时间
        //方法1：调用远程用户restfull 校验服务
        //方法2：调用数据库接口校验

//        List<ServerSession> l = sessionManger.getSessionsBy(user.getUserId());
//
//
//        if (null != l && l.size() > 0)
//        {
//            return false;
//        }

        return true;

    }
}
